package ui;
import ui.LoginJFrame;
import ui.GameJFrame;
import ui.RegisterJFrame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;

public class LoginJFrame extends JFrame implements ActionListener {
    private JTextField username;
    private JPasswordField passwordField;
    private JTextField verifyCodeField;
    private JButton refreshButton;
    private String currentCaptcha;
    private CaptchaPanel captchaPanel;
    //
    boolean flag = false;//是否被点击
    //背景
    JLabel background = new JLabel(new ImageIcon("image/login/background.png"));
    //登录按钮
    JButton loginJButton = new JButton(new ImageIcon("image/login/登录按钮.png"));

    //用户集合


    public LoginJFrame() {
        // 初始化登录界面
        initLoginFrame();
    }

    // 刷新界面
    private void initLoginFrame() {
        // 设置宽高
        this.setSize(488, 430);
        // 设置标题
        this.setTitle("登录界面 用户名:admin 密码:123456 注册还没实现，但可以按");

        // 居中
        this.setLocationRelativeTo(null);

        // 关闭方式
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        // 页面置首
        this.setAlwaysOnTop(true);

        // 添加美化背景图片
        initBackground();

        //用户栏
        inituesrJLabel();

        // 添加密码图片
        initPasswordJLabel();

        // 添加登录 JLabel
        initLoginJButton();

        // 添加注册按钮JButton
        initRegisterJButton();

        // 添加验证码图片JLabel
        initVerifyCodeJLabel();

        // 添加按钮监听器
        addButtonListeners();

        // 设置可见
        this.setVisible(true);
    }

    //背景
    private void initBackground() {
        // 添加背景图片
        background.setBounds(0, 0, 488, 430);

        this.getContentPane().add(background);
    }

    //登录框区域
    private void inituesrJLabel() {

        // 添加用户名图片
        JLabel user = new JLabel(new ImageIcon("image/login/用户名.png"));
        user.setBounds(125, 135, 47, 17);
        background.add(user);

        // 添加用户名文本框
        username = new JTextField();
        username.setBounds(188, 133, 200, 32);
        //文本框去掉尖角
        username.setBorder(null);
        background.add(username);

    }

    private void initPasswordJLabel() {
        // 添加密码图片
        JLabel password = new JLabel(new ImageIcon("image/login/密码.png"));
        password.setBounds(125, 185, 32, 16);
        background.add(password);

        // 添加密码文本框
        passwordField = new JPasswordField();
        passwordField.setBounds(188, 180, 200, 32);
        //文本框去掉尖角
        passwordField.setBorder(null);
        background.add(passwordField);
    }

    //
    private void initLoginJButton() {
        JButton loginJButton = new JButton(new ImageIcon("image/login/登录按钮.png"));
        loginJButton.setBounds(125, 288, 128, 47);
        // 去掉按钮边框
        loginJButton.setBorder(null);
        background.add(loginJButton);
    }

    // 添加注册按钮JButton
    private void initRegisterJButton() {
        JLabel registerLabel = new JLabel(new ImageIcon("image/login/注册按钮.png"));
        registerLabel.setBounds(263, 288, 128, 47);
        // 去掉按钮边框
        registerLabel.setBorder(null);
        background.add(registerLabel);
    }

    // 添加验证码图片JLabel
    private void initVerifyCodeJLabel() {
        JLabel verifyCode = new JLabel(new ImageIcon("image/login/验证码.png"));
        verifyCode.setBounds(125, 250, 56, 21);
        background.add(verifyCode);

        // 添加验证码文本框
        verifyCodeField = new JTextField();
        verifyCodeField.setBounds(188, 250, 67, 32);
        //文本框去掉尖角
        verifyCodeField.setBorder(null);
        background.add(verifyCodeField);

        // 添加刷新验证码按钮
        refreshButton = new JButton("刷新");
        refreshButton.setBounds(348, 250, 60, 32);
        refreshButton.setBackground(Color.white);
        refreshButton.setBorder(null);
        background.add(refreshButton);

        // 验证码面板
        captchaPanel = new CaptchaPanel();
        captchaPanel.setBounds(260, 250, 80, 32);
        background.add(captchaPanel);

        // 生成初始验证码
        generateAndDisplayCaptcha();
    }

    // 生成并显示验证码
    private void generateAndDisplayCaptcha() {
        currentCaptcha = generateCaptcha();
        captchaPanel.setCaptcha(currentCaptcha);
        captchaPanel.repaint();
    }

    // 生成随机验证码的方法
    private String generateCaptcha() {
        Random random = new Random();
        StringBuilder captcha = new StringBuilder();
        // 随机确定数字出现的位置
        int digitPosition = random.nextInt(4);
        for (int i = 0; i < 4; i++) {
            if (i == digitPosition) {
                // 生成一个 0 - 9 的随机数字
                captcha.append(random.nextInt(10));
            } else {
                // 生成一个随机字母（大写）
                char letter = (char) (random.nextInt(26) + 'A');
                captcha.append(letter);
            }
        }
        return captcha.toString();
    }

    // 添加按钮监听器的方法
    private void addButtonListeners() {
        refreshButton.addActionListener(this);

        JButton loginJButton = (JButton) background.getComponent(4); // 根据添加顺序获取登录标签
        loginJButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent evt) {
                actionPerformed(new ActionEvent(loginJButton, ActionEvent.ACTION_PERFORMED, "login"));
            }
        });

        JLabel registerLabel = (JLabel) background.getComponent(5); // 根据添加顺序获取注册标签
        registerLabel.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent evt) {
                actionPerformed(new ActionEvent(registerLabel, ActionEvent.ACTION_PERFORMED, "register"));
            }
        });
    }

    //添加鼠标监听器
    @Override
    public void actionPerformed(ActionEvent e) {
        initLoginJButton();
        // 刷新验证码
        if (e.getSource() == refreshButton) {
            generateAndDisplayCaptcha();
        }
        //登录按钮被按了
        if (e.getActionCommand().equals("login")) {
//            //是否被点击
//            flag=e.getActionCommand().equals("login");
//            //刷新登录按钮图片
//            initLoginJButton();


            if (!checkInput()) {
                return;
            }
            if (!checkCaptcha()) {
                return;
            }
            if (checkCredentials()) {
                JOptionPane.showMessageDialog(this, "登录成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
                GameJFrame game = new GameJFrame();
            } else {
                JOptionPane.showMessageDialog(this, "用户名或密码错误", "提示", JOptionPane.ERROR_MESSAGE);
            }
        }

        //注册按钮被按了
        if (e.getActionCommand().equals("register")){
            JOptionPane.showMessageDialog(this, "未发放", "提示", JOptionPane.INFORMATION_MESSAGE);
            //跳转注册页面
            //关闭本页面
//            this.dispose();
//            RegisterJFrame register = new RegisterJFrame();
//            JOptionPane.showMessageDialog(this, "注册成功,请返回登录", "提示", JOptionPane.INFORMATION_MESSAGE);

        }
    }

    private boolean checkInput() {
        String inputUsername = username.getText();
        String inputPassword = new String(passwordField.getPassword());
        String inputCaptcha = verifyCodeField.getText();
        if (inputUsername.isEmpty() || inputPassword.isEmpty() || inputCaptcha.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入用户名、密码和验证码", "提示", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        return true;
    }

    private boolean checkCaptcha() {
        String inputCaptcha = verifyCodeField.getText();
        if (!inputCaptcha.equalsIgnoreCase(currentCaptcha)) {
            JOptionPane.showMessageDialog(this, "验证码输入错误", "提示", JOptionPane.ERROR_MESSAGE);
            generateAndDisplayCaptcha();
            return false;
        }
        return true;
    }

    // 这里可以添加用户名和密码验证逻辑，例如查询数据库
    private boolean checkCredentials() {
        String inputUsername = username.getText();
        String inputPassword = new String(passwordField.getPassword());
        // 这里可以添加用户名和密码验证逻辑，例如查询数据库
        // 假设用户名是 "admin"，密码是 "123456"
        return "admin".equals(inputUsername) && "123456".equals(inputPassword);
    }

    // 自定义验证码面板类
    class CaptchaPanel extends JPanel {
        private String captcha;

        public void setCaptcha(String captcha) {
            this.captcha = captcha;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Random random = new Random();

            // 绘制背景
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, getWidth(), getHeight());

            // 绘制干扰线
            for (int i = 0; i < 5; i++) {
                g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
                int x1 = random.nextInt(getWidth());
                int y1 = random.nextInt(getHeight());
                int x2 = random.nextInt(getWidth());
                int y2 = random.nextInt(getHeight());
                g.drawLine(x1, y1, x2, y2);
            }

            // 绘制干扰点
            for (int i = 0; i < 20; i++) {
                g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
                int x = random.nextInt(getWidth());
                int y = random.nextInt(getHeight());
                g.drawRect(x, y, 1, 1);
            }

            // 绘制验证码文字
            g.setFont(new Font("Arial", Font.BOLD, 20));
            for (int i = 0; i < captcha.length(); i++) {
                g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
                g.drawString(String.valueOf(captcha.charAt(i)), 10 + i * 15, 22);
            }
        }
    }
}
